package com.imooc.reader.management.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imooc.reader.management.dto.ResponseDTO;
import com.imooc.reader.management.entity.User;
import com.imooc.reader.management.mapper.UserMapper;
import com.imooc.reader.management.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("")
    public ResponseDTO createUser(String username, String password, String empName, String deptName) {
        User user = userService.createUser(username, password, empName, deptName);
        user.setPassword(null);
        return new ResponseDTO().put("user", user);
    }

    @GetMapping("")
    public ResponseDTO selectByRoleCode(Integer page,Integer rows) {
        if (page == null) {
            page = 1;
        }
        if (rows == null) {
            rows = 10;
        }
        IPage<User> user = userService.selectByRoleCode(new Page(page, rows), "USER");
        // 将敏感信息脱敏处理，返回后也不再做序列化处理
        for (User u : user.getRecords()) {
            u.setPassword(null);
        }
        return new ResponseDTO().put("list", user.getRecords()).put("count", user.getTotal());
    }

    @PutMapping("/{userId}")
    public ResponseDTO updateBasicInfo(@PathVariable("userId") Integer userId, String empName, String deptName) {
        User user = userService.updateBasicInfo(userId, empName, deptName);
        user.setPassword(null);
        return new ResponseDTO().put("user", user);
    }

    @PutMapping("/{userId}/status")
    public ResponseDTO updateStatus(@PathVariable("userId") Integer userId) {
        User user = userService.updateStatus(userId);
        user.setPassword(null);
        return new ResponseDTO().put("detail",user.getUsername() + "已" + (user.getStatus() == 1 ? "启用" : "停用"));
    }

    @DeleteMapping("{userId}")
    public ResponseDTO deleteUser(@PathVariable("userId") Integer userId) {
        User user = userService.deleteUser(userId);
        user.setPassword(null);
        return new ResponseDTO().put("user",user);
    }

}
